/*
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
 */

package com.phonegap.misxv;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.annotation.SuppressLint;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;

import org.apache.cordova.*;

public class Misxv extends CordovaActivity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.init();
		// Set by <content src="index.html" /> in config.xml
		Config.init(this);
		

		String archivo = Environment.getDataDirectory() + "/data/com.phonegap.misxv/app_database/file__0/0000000000000001.db";
		File file = new File(archivo);
		if(!file.exists()){
			Log.i("MISXV","Creando la base de datos.");
//			//CODIGO PARA BORRAR LA BASE DE DATOS 
////			file.delete(); 
			verificarExistenciaBaseDatos();
		}
//		verificarExistenciaBaseDatos();
//		exportDB();//quitar esta llamada al finalizar la app
//		
//		
//		String archivo = Environment.getDataDirectory() + "/data/com.phonegap.misxv/app_database/file__0/";
//		File file = new File(archivo);
//		File file2[] = file.listFiles();
////        Log.d("Files", "Size: "+ file2.length);
//        for (int i=0; i < file2.length; i++)
//        {
//            Log.d("Files", "FileName:" + file2[i].getName());
//        }
//		
//		
//		verificarExistenciaBaseDatos();
		
		
		
		
		 super.loadUrl("file:///android_asset/www/enterApp.html");
//		super.loadUrl(Config.getStartUrl());
	}

	private void getAppKeyHash() {
	    try {
	    	
	        PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES);
	        for (Signature signature : info.signatures) {
	            MessageDigest md;

	            md = MessageDigest.getInstance("SHA");
	            md.update(signature.toByteArray());
	            String something = new String(Base64.encode(md.digest(), 0));
	            Log.i("La Hash key es", something);
	        } 
	    }
	    catch (NameNotFoundException e1) {
	        // TODO Auto-generated catch block
	        Log.i("name not found", e1.toString());
	    }

	    catch (NoSuchAlgorithmException e) {
	        // TODO Auto-generated catch block
	        Log.i("no such an algorithm", e.toString());
	    }
	    catch (Exception e){
	        Log.i("exception", e.toString());
	    }

	}
	
	
	@SuppressLint("SdCardPath") public void verificarExistenciaBaseDatos() {
		try {
			String pName = this.getClass().getPackage().getName();
			this.copy("Databases.db", "/data/data/" + pName + "/app_database/");
			this.copy("0000000000000001.db","/data/data/"+pName+"/app_database/file__0/");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	void copy(String file, String folder) throws IOException {
		File CheckDirectory;
		CheckDirectory = new File(folder);
		if (!CheckDirectory.exists()) {
			CheckDirectory.mkdir();
		}

		InputStream in = getApplicationContext().getAssets().open(file);
		OutputStream out = new FileOutputStream(folder + file);

		// Transfer bytes from in to out
		byte[] buf = new byte[1024];
		int len;
		while ((len = in.read(buf)) > 0)
			out.write(buf, 0, len);
		in.close();
		out.close();
	}

	private void exportDB() {

		final File sd = Environment.getExternalStorageDirectory();
		final File data = Environment.getDataDirectory();
		final String rutaBaseDatosLocal = Environment.getDataDirectory()
				+ "/com.phonegap.misxv/app_database/file__0/";
		final String nombreBaseDatosLocal = "0000000000000001.db";
		final String directorioAplicacion = "Misxv";
		
		FileChannel source = null;
		FileChannel destination = null;
		String pathBaseDatosLocal = rutaBaseDatosLocal + nombreBaseDatosLocal;
		String pathBackup = "/" + directorioAplicacion + "/"
				+ nombreBaseDatosLocal;
		File currentDB = new File(data, pathBaseDatosLocal);
		File backupDB = new File(sd, pathBackup);
		try {
			source = new FileInputStream(currentDB).getChannel();
			destination = new FileOutputStream(backupDB).getChannel();
			destination.transferFrom(source, 0, source.size());
			source.close();
			destination.close();
			Log.i("MISXV","BASE DE DATOS EXPORTADA");
		} catch (IOException e) {
			e.printStackTrace();
			Log.i("MISXV","OCURRIO UN ERROR AL EXPORTAR LA BASE DE DATOS");
		}
	}
	
	@Override
	public void onBackPressed() {
	    super.loadUrl("javascript:onBackKeyDown()");
	    return;
	}
	
}
